package cn.b.sky.mes.andon.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.b.sky.mes.andon.enums.AndonAtributeType;
import cn.b.sky.mes.andon.model.AndonAttribute;
import cn.b.sky.mes.andon.model.AndonAttributeEnum;
import cn.b.sky.mes.andon.model.condition.AndonAttributeCondition;
import cn.b.sky.mes.andon.service.AndonAttributeService;
import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.enums.DwzCallbackType;
import cn.b.sky.common.enums.DwzStatusCode;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;

@Controller
@RequestMapping("/andonAttribute/*")
public class AndonAttributeController extends SecurityController {
  
  private static final String ECODE = "ECode";  
  
  private static final String PATTERN = "pattern";
  
  @Resource
  AndonAttributeService andonAttributeService;
  
  @Resource
  ECodeService eCodeService;
  
  @RequestMapping("andonAttribute_list")
  public String selectAndonAttributeListByCondition(@ModelAttribute("condition") AndonAttributeCondition condition,
      String navTabId, Model model){
    condition.setSiteCode(getSiteCode());
    if (StringUtils.isEmpty(condition.getOrderField())) {
      condition.setOrderField("createDateTime");
    }
    List<AndonAttribute> list = andonAttributeService.selectAndonAttributeByCondition(condition);
    int count =andonAttributeService.selectAndonAttributeCount(condition);
    condition.setTotalCount(count);
    condition.setData(list);
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.ANDONATTRIBUTETYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute(ECODE, ecode);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("page", condition);
    return "andon/andonAttribute/andonAttribute_list";
  }
  
  @RequestMapping("addAndonAttribute")
  public String addDefectAttribute(String navTabId, Model model) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute(PATTERN, "add");
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.ANDONATTRIBUTETYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute(ECODE, ecode);
    return "andon/andonAttribute/andonAttribute_add";
  }
  
  @RequestMapping("saveAndonAttribute")
  @ResponseBody
  public DWZResult saveDefectAttribute(String id, AndonAttribute attribute, String navTabId, Model model) {
    if (attribute == null || StringUtils.isBlank(attribute.getAttributeCode())) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }

    if (AndonAtributeType.ENUM.getValue().equals(attribute.getValueTypeEcode()) && attribute.getAttributeValue() != null) {
      for (String value : attribute.getAttributeValue()) {
        if(!StringUtils.isBlank(value)){
          AndonAttributeEnum attributeEnum = new AndonAttributeEnum(getSiteCode(), attribute.getAttributeCode(), value);
          setCreateInfo(attributeEnum);
          attribute.getAttributeEnumList().add(attributeEnum);
        }
      }
    }
    attribute.setSiteCode(getSiteCode());
    setCreateInfo(attribute);
    if (StringUtils.isBlank(id)) {
      andonAttributeService.insertAndonAttribute(attribute);
    } else {
      andonAttributeService.updateAndonAttribute(attribute);
    }
    return dialogAjaxDone(
        getImeViewMessageI18n(null, "successfulOperation.M"),
        null, null, null, null);
  }
  
  @RequestMapping("validateAndonAttributeCode")
  @ResponseBody
  public boolean validateAndonAttributeCode(String attributeCode) {
    if (StringUtils.isBlank(attributeCode)) {
      return true;
    } else {
      AndonAttribute attribute = andonAttributeService.selectAndonAttribute(getSiteCode(), attributeCode);
      return attribute == null;
    }
  }

  @RequestMapping("changeDialogSize")
  @ResponseBody
  public DWZResult changeDialogSize(String andonAttributeCode, String navTabId, HttpServletRequest request) {
    if (StringUtils.isBlank(andonAttributeCode)) {
      return ajaxError(this.getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }

    AndonAttribute attribute = andonAttributeService.selectAndonAttribute(getSiteCode(), andonAttributeCode);
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("title",
        getImeViewMessageI18n(null, "viewAndonAttribute.D"));
    String forwardUrl = request.getContextPath() + "/manage/andonAttribute/viewAndonAttribute?id="
        + attribute.getAttributeCode();
    if (attribute.getValueTypeEcode().equals(AndonAtributeType.ENUM.getValue())) {
      map.put("type", "enum");
    }
    String jsonData = JSON.toJSONString(map);
    return getDWZJsonObject(DwzStatusCode.OK, null, navTabId, "viewAndonAttribute", DwzCallbackType.EMPTY, forwardUrl,
        null, jsonData);
  }
  
  @RequestMapping("modifyAndonAttribute")
  public String modifyDefectAttribute(String id, String navTabId, Model model) {
    AndonAttribute attribute = andonAttributeService.selectAndonAttribute(getSiteCode(), id);
    if (attribute.getValueTypeEcode().equals(AndonAtributeType.ENUM.getValue())) {
      attribute.getAttributeEnumList().addAll(
          andonAttributeService.selectAndonAttributeEnumByAttribute(getSiteCode(), id));
    }
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.ANDONATTRIBUTETYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute(ECODE, ecode);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("andonAttribute", attribute);
    model.addAttribute(PATTERN, "modify");

    return "andon/andonAttribute/andonAttribute_add";
  }
  
  @RequestMapping("viewAndonAttribute")
  public String viewDefectAttribute(String id, String navTabId, Model model) {
    AndonAttribute attribute =andonAttributeService.selectAndonAttribute(getSiteCode(), id);
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.ANDONATTRIBUTETYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    String view = "andon/andonAttribute/andonAttribute_view";
    if (AndonAtributeType.ENUM.getValue().equals(attribute.getValueTypeEcode())) {
      attribute.getAttributeEnumList().addAll(
          andonAttributeService.selectAndonAttributeEnumByAttribute(getSiteCode(), id));
      view = "andon/andonAttribute/andonAttribute_EnumView";
    }
    model.addAttribute(ECODE, ecode);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("andonAttribute", attribute);
    model.addAttribute(PATTERN, "view");

    return view;
  }
  
  @RequestMapping("deleteAndonAttribute")
  @ResponseBody
  public DWZResult deleteAndonAttribute(Model model, String navTabId, String id, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isEmpty(ids)) {
      return ajaxError(getImeViewMessageI18n(null, SystemConstant.PARAMETERNULL));
    }
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = andonAttributeService.deleteAndonAttribute(getSiteCode(), res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null, getImeViewMessageI18n(null, "successfulOperation.M"), null);
    } else {
      return batchjobAjaxDone(request, reports);
    }

  }
  
  @RequestMapping("selectAndonAttribute")
  public String selectAndonAttribute(@ModelAttribute("condition") AndonAttributeCondition condition,
      String navTabId, Model model){
    condition.setSiteCode(getSiteCode());
    if (StringUtils.isEmpty(condition.getOrderField())) {
      condition.setOrderField("createDateTime");
    }
    condition.setLockFlag(0);
    List<AndonAttribute> list = andonAttributeService.selectAndonAttributeByCondition(condition);
    int count =andonAttributeService.selectAndonAttributeCount(condition);
    condition.setTotalCount(count);
    condition.setData(list);
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.ANDONATTRIBUTETYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute(ECODE, ecode);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("page", condition);
    return "andon/andonAttribute/andonAttribute_lookUp";
  }

}
